﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tecnicas.CasoEstudio.Back.Dominio;
using Tecnicas.CasoEstudio.Repositorio;
using System.Collections;


namespace Tecnicas.CasoEstudio.Back.Persistencia
{
    public class AlquilerDataMapper : AbstractDataMapper
    {
        public AlquilerDataMapper()
        {             
        }
        

        public override object Insert(DomainObject obj)
        {
            if (typeof(Alquiler) != obj.GetType())
                throw new ApplicationException("Este mapper solo opera con objetos del tipo Alquiler");

            if (obj.PersistenceId == null)
            {
                obj.PersistenceId = RepositorioVersionado.Instance.GetNextKey();
                obj.PersistenceVersion = 0;
            }

            Alquiler alquiler = (Alquiler)obj;

            // se persisten las agregaciones
            PeliculaDataMapper peliculaDataMapper = new PeliculaDataMapper();
            Pelicula pelicula = (Pelicula)peliculaDataMapper.Insert(alquiler.Pelicula);
            alquiler.PersistenceIdPelicula = pelicula.PersistenceId;


            Alquiler alquilerCopia = this.ClonePlainObject(alquiler);

            RepositorioVersionado.Instance.Guardar(alquilerCopia, alquilerCopia.PersistenceId, alquilerCopia.PersistenceVersion, ++alquilerCopia.PersistenceVersion);

            alquiler.Pelicula.PersistenceId = pelicula.PersistenceId;
            alquiler.Pelicula.PersistenceVersion = pelicula.PersistenceVersion;

            alquiler.PersistenceVersion++;
            return alquiler;
        }

        private Alquiler ClonePlainObject(Alquiler alquiler)
        {            
            Alquiler alquilerCopia = new Alquiler(alquiler.Pelicula,alquiler.DiasAlquilada);
            alquilerCopia.PersistenceId = alquiler.PersistenceId;
            alquilerCopia.PersistenceVersion = alquiler.PersistenceVersion;
            alquilerCopia.PersistenceIdPelicula = alquiler.PersistenceIdPelicula;
            
            return alquilerCopia;
        }

        public override void Delete(long? id, object version)
        {
            RepositorioVersionado.Instance.Eliminar(typeof(Alquiler), id, version);
        }
        public override void Delete(DomainObject obj)
        {
            this.Delete(obj.PersistenceId, obj.PersistenceVersion);
        }

        public override DomainObject Find(long? id)
        {
            return (Alquiler)RepositorioVersionado.Instance.ObtenerPorId(typeof(Alquiler), id);
        }
        public override ArrayList FindAll()
        {
            return RepositorioVersionado.Instance.ObtenerPorTipo(typeof(Alquiler));
        }
       
    }
}
